import dayjs from "dayjs";
import { usePublicHooks } from "../hooks";
import { reactive, ref, onMounted, h, onBeforeMount } from "vue";
import { message } from "@/utils/message";
import { addDialog } from '@/components/ReDialog'
import { ElMessageBox } from 'element-plus'
import { type FormItemProps } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import elForm from '../form.vue'

import { RoadList, addRoad, updateRoad, delRoad, SpeedLevel, getRoad } from '@/utils/api/dispatch/road'
import { GetAllStation } from '@/utils/api/dispatch/station'
import { GetAllMap } from '@/utils/api/dispatch/map'

export function useDept() {
    const form = reactive({
        roadname: "",
        dateRange: null,
        begin: "",
        end: "",
        pageNumber: 0,
        pageSize: 10,
        sortName: "createtime",
        sortType: 0
    });

    const formRef = ref();
    const dataList = ref([]);
    const loading = ref(true);
    const { tagStyle } = usePublicHooks();
    const pagination = reactive<PaginationProps>({
        total: 0,
        pageSize: 10,
        currentPage: 1,
        background: true
    });

    // 解析站点
    function filterStation(val) {
        let station = stationSelect.value.find(v => {
            return v.stationid == val
        })
        if (station === undefined) return false;
        return station.stationname
    }

    // 状态select
    const StatusOptions = reactive([
        { value: 1, label: '启用' },
        { value: 0, label: '禁用' },
        { value: 2, label: '锁定' },
    ])

    // 动作类型select
    const actionType = reactive([
        { value: 0, label: '直线' },
        { value: 1, label: '凹弧线' },
        { value: 2, label: '凸弧线' },
        { value: 3, label: '贝塞尔曲线' }
    ])

    // 路段方向select
    const directionOptions = reactive([
        { value: 1, label: '单向' },
        { value: 2, label: '双向' },

    ])

    // 行驶方向select
    const directions = reactive([
        { value: 0, label: '倒走' },
        { value: 1, label: '正走' },
        { value: 2, label: '左移' },
        { value: 3, label: '右移' }
    ])

    // 所属地图
    var mapTypes = ref([])

    // 速度等级select
    const SpeedLevelArr = ref([])

    // 动作类型
    function formatType(status) {
        const stateMap = {
            0: '直线',
            1: '凹弧线',
            2: '凸弧线',
            3: '贝塞尔曲线'
        }
        return stateMap[status]
    }

    // 状态
    function formatStatus(status) {
        const stateMap = {
            0: '禁用',
            1: '启用',
            2: '锁定'
        }
        return stateMap[status]
    }

    // 站点select
    let stationSelect = ref([])
    // 货位站点
    let assistSelect = ref([])

    const columns: TableColumnList = [
        {
            label: "路段名称",
            prop: "name",
            width: 160,
            align: "left",
            sortable: true
        },
        {
            label: "起始站点",
            prop: "StartStationName",
            width: 130,
            align: "left",
            sortable: true
        },
        {
            label: "终点站点",
            prop: "EndStationName",
            width: 130,
            align: "left",
            sortable: true
        },
        {
            label: "路段类型",
            prop: "linetype",
            minWidth: 100,
            cellRenderer: ({ row, props }) => { return formatType(row.linetype); }
        },
        {
            label: "方向",
            prop: "direction",
            minWidth: 100,
            cellRenderer: ({ row, props }) => { return row.direction === 1 ? '单向' : '双向' }
        },
        {
            label: "路段状态",
            prop: "status",
            minWidth: 100,
            cellRenderer: ({ row, props }) => (
                <el-tag size={props.size} style={tagStyle.value(row.status)}>
                    {formatStatus(row.status)}
                </el-tag>
            )
        },
        {
            label: "备注",
            prop: "remark",
            minWidth: 200,
            align: "left"
        },
        {
            label: "操作",
            fixed: "right",
            width: 200,
            slot: "operation"
        }
    ]

    // 同步函数，用于搜索
    async function onSearch() {
        // 设置loading状态为true
        loading.value = true;
        // 调用RoadList函数，传入form参数，获取Content
        const { Content } = await RoadList(form);
        // 将Content.Results赋值给newData
        let newData = Content.Results;
        // 将newData赋值给dataList
        dataList.value = newData;
        // 将Content.TotalCount赋值给pagination.total
        pagination.total = Content.TotalCount;
        // 将Content.PageSize赋值给pagination.pageSize
        pagination.pageSize = Content.PageSize;
        // 将Content.PageNumber + 1赋值给pagination.currentPage
        pagination.currentPage = Content.PageNumber + 1;

        setTimeout(() => {
            loading.value = false;
        }, 500);
    }

    // 重置
    function resetForm(formEl) {
        if (!formEl) return;
        formEl.resetFields();
        onSearch();
    }

    function openDialog(title = "新增", row?: FormItemProps) {
        addDialog({
            title: `${title}路段`,
            props: {
                formInline: {
                    startstation: row?.startstation ?? null,
                    endstation: row?.endstation ?? null,
                    status: row?.status ?? 1,
                    direction: row?.direction ?? null,
                    mapid: row?.mapid ?? null,
                    linetype: row?.linetype ?? "",
                    assistList: row?.assistList ?? [{}],
                    note: row?.note ?? "",
                    detailList: row?.detailList ?? [{}]
                },
                stationSelect: stationSelect.value || [],
                StatusOptions: StatusOptions || [],
                actionType: actionType || [],
                SpeedLevelArr: SpeedLevelArr.value || [],
                directionOptions: directionOptions || [],
                mapTypes: mapTypes.value || [],
                directions: directions || [],
            },
            width: "45%",
            draggable: true,
            fullscreenIcon: true,
            closeOnClickModal: false,
            contentRenderer: () => h(elForm, { ref: formRef }),
            beforeSure: (done, { options }) => {
                const FormRef = formRef.value.getRef();
                const curData = options.props.formInline as FormItemProps;
                function chores() {
                    message(`您${title}了路段名称为${curData.roadname}的这条数据`, {
                        type: "success"
                    });
                    done(); // 关闭弹框
                    onSearch(); // 刷新表格数据
                }
                FormRef.validate(valid => {
                    if (valid) {
                        console.log("curData", curData);
                        // 拼接路段名称
                        curData.roadname = `${filterStation(curData.startstation)}-${filterStation(curData.endstation)}`
                        // 表单规则校验通过
                        if (title === "新增") {
                            addRoad(curData).then(res => {
                                if (res.Code === 0) chores();
                            })
                        } else {
                            let data = Object.assign(curData, { id: row.id })
                            updateRoad(data).then(res => {
                                if (res.Code === 0) chores();
                            })
                        }
                    }
                });
            }
        })
    }

    // 删除
    function handleDelete(row) {
        ElMessageBox.confirm(
            `是否确认删除名称为${row.name}的数据项?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            delRoad(row.id).then(res => {
                if (res.Code === 0) {
                    message(`您删除了名称为${row.name}的这条数据`, { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    function handleSizeChange(val: number) {
        form.pageSize = val
        onSearch()
    }

    function handleCurrentChange(val: number) {
        form.pageNumber = val - 1
        onSearch()
    }

    onBeforeMount(async () => {
        // 站点下拉
        let { Content: station } = await GetAllStation()
        stationSelect.value = station
        // 货位站点
        let { Content: ssist } = await GetAllStation({ status: 1, stationType: 3 })
        assistSelect.value = ssist
        // 速度等级下拉
        let { Content: Speed } = await SpeedLevel()
        SpeedLevelArr.value = Speed
        // 地图select
        let { Content: map } = await GetAllMap()
        mapTypes.value = map
    })

    onMounted(() => {
        onSearch()
    })

    return {
        columns,
        loading,
        dataList,
        openDialog,
        handleDelete,
        form,
        onSearch,
        resetForm,
        pagination,
        handleSizeChange,
        handleCurrentChange,
        filterStation
    }
}